<template>
  <div class="manualContainer">
    <div class="headerContainer">
      <FormQuery
        ref="formQuery"
        :initial-form-data="initialFormData"
        @query="handleQuery"
        @reset="handleReset"
      />
    </div>
    
    <div class="contentContainer">
      <el-table
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          prop="batchNo"
          label="批号"
          width="180"
          align="center"
        />
        
        <el-table-column
          prop="targetType"
          label="目标类型"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <span class="target-type-badge">
              {{ mapTargetType(scope.row.targetType) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="trackNum"
          label="航迹数量"
          align="center"
        />
        
        <el-table-column
          prop="targetTypeManual"
          label="人工修正类型"
          align="center"
        >
          <template slot-scope="scope">
            <div class="editable-cell">
              <el-select
                v-if="scope.row.editing"
                v-model="scope.row.targetTypeManual"
                placeholder="请选择"
                size="mini"
               @change="handleTypeChange(scope.row)"
          @visible-change="handleSelectVisible"
              >
                <el-option
                  v-for="item in frequencyData"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
              <div 
                v-else
                class="editable-content"
                @click="startEditing(scope.row)"
              >
                {{ mapTargetType(scope.row.targetTypeManual) }}
                <span class="edit-hint">点击编辑</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="relatedRealNo"
          label="关联真实批号"
          align="center"
        />
        
        <el-table-column
          prop="relatedRealFlag"
          label="关联真实标识"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.relatedRealFlag ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.relatedRealFlag ? '已关联' : '未关联' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import FormQuery from "@/components/FormQuery/index.vue";
import { getTrackBatchList, saveTrackBatchManual } from '@/api/datarecord/index.js';
import {
  getDict,
} from "@/api/service";
// 目标类型映射关系
const TARGET_TYPE_MAP = {
  1: { label: '飞机', color: '#409eff' },
  2: { label: '船舶', color: '#67c23a' },
  3: { label: '车辆', color: '#e6a23c' },
  4: { label: '导弹', color: '#f56c6c' },
  5: { label: '卫星', color: '#909399' },
  6: { label: '无人机', color: '#9e6fff' },
  7: { label: '不明目标', color: '#ff85c0' },
};

export default {
  components: {
    FormQuery
  },
  data() {
    return {
       targetTypeDict: {},
      frequencyData:[],
      initialFormData: {
        dateRange: [],
        targetType: "",
        batchNo: "",
      },
      queryResult: {},
      tableData: [],
      total: 40,
      pageSize: 10,
      currentPage: 1,
    };
  },
  async created() {
    await this.loadDict(); // 确保字典加载完成
    this.getDataTableHandle();
  },
  mounted() {
    this.getDataTableHandle();
  },
  methods: {
    // 目标类型映射
      mapTargetType(type) {
      if (type === null || type === undefined) return '未知类型';
      return this.targetTypeDict[type] || '未知类型';
    },
    
    // 获取目标类型样式类
    getTargetTypeClass(type) {
      return `type-${type}`;
    },
     // 修改：获取字典数据后构建映射表
    async loadDict() {
      try {
        const res = await getDict("sys_target_type");
        if (res.code === 200) {
          this.frequencyData = res.data;
          
          // 构建字典映射表 {值: 标签}
          this.targetTypeDict = res.data.reduce((dict, item) => {
            dict[item.dictValue] = item.dictLabel;
            return dict;
          }, {});
        }
      } catch (error) {
        console.error('字典加载失败', error);
      }
    },
    
    // 修改：确保编辑状态响应性
 startEditing(row) {
      this.tableData.forEach(item => {
        this.$set(item, 'editing', false);
      });
      this.$set(row, 'editing', true);
      this.$set(row, 'originalType', row.targetTypeManual);
      
      // 确保DOM更新后聚焦到选择框
      this.$nextTick(() => {
        if (this.$refs.typeSelect) {
          this.$refs.typeSelect.focus();
        }
      });
    },
    
    // 完成编辑
    finishEditing(row) {
      if (row.editing) {
        this.$set(row, 'editing', false);
      }
    },
    
    // 类型变更处理
      handleTypeChange(row) {
      console.log(`类型变更为: ${this.mapTargetType(row.targetTypeManual)}`);
      // 立即更新视图
      this.$forceUpdate();
      this.autoSaveChanges(row);
    },
    autoSaveChanges(row) {
  // 清除之前的定时器
  clearTimeout(this.autoSaveTimer);
  
  // 设置新的保存定时器（1秒后保存）
  this.autoSaveTimer = setTimeout(async () => {
    try {
      this.$set(row, 'saving', true);
      const res = await saveTrackBatchManual({
        uniqueBatchNo: row.uniqueBatchNo,
        manualTargetType: row.targetTypeManual
      });
      
      if (res.code === 200) {
        this.$message.success('自动保存成功');
        this.$set(row, 'editing', false);
        this.getDataTableHandle()
      }
    } catch (error) {
      this.$message.error('保存失败');
    } finally {
      this.$set(row, 'saving', false);
    }
  }, 1000);
},
    handleSelectVisible(visible) {
      // 当下拉框关闭时（选择完成），不立即结束编辑
      if (!visible) {
        // 延迟处理确保选择值已更新
        setTimeout(() => {
          // 这里可以添加额外的处理逻辑
        }, 100);
      }
    },

    
    // 行样式处理
    tableRowClassName({ rowIndex }) {
      return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getDataTableHandle();
    },
    
    // 当前页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getDataTableHandle();
    },
    
    async getDataTableHandle() {
      let params={
        batchNo:this.queryResult.batchNo,
        targetType:this.queryResult.targetType
      }
      try {
       const res= await getTrackBatchList(params)
       if(res.code==200){
         this.tableData = res.rows;
       }
        
      } catch (error) {
        console.error('获取数据失败:', error);
        this.$message.error('数据加载失败');
      }
    },
    
    handleQuery(formData) {
      this.queryResult = { ...formData };
      this.getDataTableHandle();
    },
    
    handleReset() {
      this.queryResult = null;
      this.$message.info("已清除查询条件");
      this.getDataTableHandle();
    }
  }
};
</script>

<style lang="scss" scoped>
.manualContainer {
  height: 100vh;
  background-color: #0e1832;
  padding: 20px;
  display: flex;
  flex-direction: column;
  
  .headerContainer {
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    border-bottom: 1px solid rgba(13, 138, 188, 0.3);
    background-color: #0f3350;
    border-radius: 8px;
    height: 60px;
    color: #fff;
    padding: 0 20px;
  }
  
  .contentContainer {
    flex: 1;
    background-color: #0f3350;
    border-radius: 8px;
    padding: 15px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .pagination-container {
      padding: 20px 0;
      display: flex;
      justify-content: center;
      flex-shrink: 0;
    }
    
    .editable-cell {
      min-height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .editable-content {
        cursor: pointer;
        padding: 5px 10px;
        border-radius: 4px;
        transition: all 0.3s;
        position: relative;
        
        &:hover {
          background-color: rgba(13, 138, 188, 0.2);
          
          .edit-hint {
            opacity: 1;
          }
        }
        
        .edit-hint {
          position: absolute;
          top: 100%;
          left: 0;
          right: 0;
          font-size: 10px;
          text-align: center;
          color: #7fdbff;
          opacity: 0;
          transition: opacity 0.3s;
        }
      }
    }
    
    .target-type-badge {
      display: inline-block;
      padding: 4px 10px;
      border-radius: 12px;
      font-size: 12px;
      font-weight: 500;
      
      &.type-1 { background-color: rgba(64, 158, 255, 0.2); color: #409eff; }
      &.type-2 { background-color: rgba(103, 194, 58, 0.2); color: #67c23a; }
      &.type-3 { background-color: rgba(230, 162, 60, 0.2); color: #e6a23c; }
      &.type-4 { background-color: rgba(245, 108, 108, 0.2); color: #f56c6c; }
      &.type-5 { background-color: rgba(144, 147, 153, 0.2); color: #909399; }
      &.type-6 { background-color: rgba(158, 111, 255, 0.2); color: #9e6fff; }
      &.type-7 { background-color: rgba(255, 133, 192, 0.2); color: #ff85c0; }
    }
    
    // 表格样式覆盖
    ::v-deep .el-table {
      background-color: transparent;
      flex: 1;
      overflow: auto;
      
      th, tr {
        background-color: #0a2139;
      }
      
      td {
        background-color: #0f3350;
        border-bottom: 1px solid #0a2139;
      }
      
      th {
        color: #5ab4e0;
        border-bottom: 1px solid #0a2139;
        font-size: 14px;
        font-weight: 500;
      }
      
      tr:hover td {
        background-color: #0a2945 !important;
      }
      
      .cell {
        color: #c0e4ff;
      }
      
      &::before {
        height: 0;
      }
      
      // 单数行样式
      .odd-row {
        background: linear-gradient(
          90deg,
          rgba(13, 138, 188, 0.1) 0%,
          rgba(13, 138, 188, 0.05) 100%
        );
      }
      
      // 双数行样式
      .even-row {
        background: linear-gradient(
          90deg,
          rgba(79, 172, 254, 0.1) 0%,
          rgba(79, 172, 254, 0.05) 100%
        );
      }
      
      // 悬停效果
      .odd-row:hover > td {
        background: linear-gradient(
          90deg,
          rgba(13, 138, 188, 0.3) 0%,
          rgba(13, 138, 188, 0.2) 100%
        ) !important;
      }
      
      .even-row:hover > td {
        background: linear-gradient(
          90deg,
          rgba(79, 172, 254, 0.3) 0%,
          rgba(79, 172, 254, 0.2) 100%
        ) !important;
      }
    }
    
    // 分页样式调整
    ::v-deep .el-pagination {
      .btn-next, .btn-prev, .el-pager li {
        background-color: rgba(13, 138, 188, 0.2);
        color: #7fdbff;
        border: 1px solid #0d8abc;
        margin: 0 4px;
        min-width: 30px;
        height: 30px;
        line-height: 30px;
        border-radius: 4px;
      }
      
      .el-pager li:not(.disabled).active {
        background-color: #005da5;
        color: white;
        border-color: #005da5;
      }
      
      .el-pagination__total {
        color: #7fdbff;
        font-weight: 500;
        margin-right: 10px;
      }
      
      .el-pagination__sizes {
        margin: 0 10px;
        
        .el-input {
          width: 110px;
          
          .el-input__inner {
            background-color: rgba(13, 138, 188, 0.2);
            border-color: #0d8abc;
            color: #7fdbff;
          }
        }
      }
    }
  }
}
</style>